<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE);
set_time_limit(30);
mb_internal_encoding("UTF-8");
date_default_timezone_set("Asia/Chongqing");
define("_ver", "20141107");
$arr = array_keys($_GET);
if(!isset($arr[0])) exit("0x0");
$id = $arr[0];

if($id == "alarm"){		// 抓取天气预警
	$wdata = serialize(get_weather_alarm());
}elseif($id == "update"){      // 自动更新抓取程序
	$data = get_file("http://w.mdeve.com/get.update.php?_ver=". _ver);
	if($data == "error") exit("error");
	$data = gzuncompress(base64_decode($data));
	file_put_contents("get.php", $data);
	echo "successful";exit;
}else{
	// 9位纯数字城市ID，12位最后为大写的A为风景区
	if(strlen($id)==9&&is_numeric($id) || strlen($id)==12&&substr($id, -1)=="A"){
		print_r(get_weather_from_network($id));exit;
		$wdata = serialize(get_weather_from_network($id));
		if(strlen($wdata["city_3"])<2) exit("0x09");
	}else{
		exit("0x01");
	}
}
$wdata = gzcompress($wdata);
echo base64_encode($wdata.md5($wdata));




////////////////////////////////////////////////////////////////////////////////////////////
// 天气网新版--抓取
function get_weather_from_network($id){
	$data_info = array(
			"in_flow" => 0,		// 已抓取的字节数
			"in_count" => 0,		// 抓取网页次数
			"city_1" => "",	// 省，国外城市为国家
			"city_2" => "",	// 市，城市
			"city_3" => "",	//今天明天预报/ 城区或县。国外为空
			"update_time" => "",	// 更新时间
			"realtime" => array(),		// 实时天气
			"alarm" => array(),		// 天气预警
	);

	// 国外未做识别


	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 实时天气
	$data = get_file_use_referer("http://d1.weather.com.cn/dingzhi/{$id}.html", true);
	$data_info["in_count"] ++;		// 抓取次数
	$data_info["in_flow"] += strlen($data);		// 本次抓取字节
	if(strlen($data) > 50) {
		// 提取天气json
		$s_weather = skip_to_str($data, "=");
		$s_weather = get_front_str($s_weather, ";");
		$s_weather = json_decode($s_weather, true);
		$data_info["realtime"] = $s_weather["weatherinfo"];
		// 提取预警json
		$s_alarm = skip_to_str($data, ";");
		$s_alarm = skip_to_str($s_alarm, "=");
		$s_alarm = json_decode($s_alarm, true);
		$data_info["alarm"] = $s_alarm["w"];
	}

	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	/* 抓取并分析天气网页--今天 */
	$data = get_file_use_referer("http://www.weather.com.cn/weather1d/{$id}.shtml");
	$data_info["in_count"] ++;		// 抓取次数
	$data_info["in_flow"] += strlen($data);		// 本次抓取字节
	// 清理掉不需要的内容
	$data = skip_to_str($data, "<input id=\"whichDay\" type=\"hidden\" value=\"today\" />");
	$data = skip_to_str($data, "<div class=\"crumbs fl\">");
	$_code_box = get_front_str($data, "</div>");
	preg_match_all('/[\x{4e00}-\x{9fa5}]+/u', $_code_box, $matches);
	if(isset($matches[0][0])) $data_info["city_1"] = $matches[0][0];
	if(isset($matches[0][1])) $data_info["city_2"] = $matches[0][1];
	if(isset($matches[0][2])) $data_info["city_3"] = $matches[0][2];

	// 分析天气发布时间
	$data = skip_to_str($data, "<div class=\"today clearfix\" id=\"today\">");
	$_code_box = get_front_str($data, "<div class=\"t\">");
	preg_match_all('/fc_24h_.*?value\="(.*?)"/is', $_code_box, $matches);
	if(isset($matches[1][0])) {
		$data_info["update_time"] = date("Y-m-d H:i", strtotime($matches[1][0]));
	}

	// 分析白天天气
	$data = skip_to_str($data, "<li>");
	$_code_box = get_front_str($data, "</ul>");
	$today = array(
		"weather_day" => "",
		"temperature_day" => "",
		"wind_direction_day" => "",
		"wind_power_day" => "",
		"sun_up" => "",
		"weather_night" => "",
		"temperature_night" => "",
		"wind_direction_night" => "",
		"wind_power_night" => "",
		"sun_down" => "",
	);
	// 匹配天气
	preg_match_all('/class="wea".+?>(.+?)</is', $_code_box, $matches);
	if(sizeof($matches[1])) {
		$today["weather_day"] = $matches[1][0];
		$today["weather_night"] = $matches[1][1];
	}
	// 匹配温度
	preg_match_all('/<p class=\"tem\">.*?<span>(.+?)<\/span><em>(.+?)<\/em>/is', $_code_box, $matches);
	if(sizeof($matches[1])) {
		$today["temperature_day"] = $matches[1][0]. $matches[2][0];
		$today["temperature_night"] = $matches[1][1]. $matches[2][1];
	}
	// 匹配风向风力
	preg_match_all('/<p class=\"win\">.*?title=\"(.+?)\">(.+?)<\/span>/is', $_code_box, $matches);
	if(sizeof($matches[1])) {
		$today["wind_direction_day"] = $matches[1][0];
		$today["wind_power_day"] = $matches[1][1];
		$today["wind_direction_night"] = $matches[2][0];
		$today["wind_power_night"] = $matches[2][1];
	}
	// 日出日落
	preg_match_all('/<p class=\"sun.*?<span>(.+?)<\/span>/is', $_code_box, $matches);
	if(sizeof($matches[1])) {
		$sun_up = explode(" ", $matches[1][0]);
		$sun_down = explode(" ", $matches[1][1]);
		$today["sun_up"] = $sun_up[1];
		$today["sun_down"] = $sun_down[1];
	}
	$data_info["today"] = $today;


	// 生活指数（国外没有生活指数）
	$data = skip_to_str($data, "<div class=\"livezs\">");
	$data = skip_to_str($data, "<ul class=\"clearfix\">");
	$_code_box = get_front_str($data, "</ul>");
	$index_hot = array_fill(0, 6, array("important"=>"", "content"=>"", "title"=>""));
	// 强度
	preg_match_all('/<span>(.+?)<\/span>/is', $_code_box, $matches);
	if(sizeof($matches[1])) {
		for($i=0; $i<sizeof($matches[1]); $i++){
			$index_hot[$i]["important"] = $matches[1][$i];
		}
	}
	// 类别
	preg_match_all('/<em>(.+?)<\/em>/is', $_code_box, $matches);
	if(sizeof($matches[1])) {
		for($i=0; $i<sizeof($matches[1]); $i++){
			$index_hot[$i]["title"] = $matches[1][$i];
		}
	}
	// 内容
	preg_match_all('/<p>(.+?)<\/p>/is', $_code_box, $matches);
	if(sizeof($matches[1])) {
		for($i=0; $i<sizeof($matches[1]); $i++){
			$index_hot[$i]["content"] = $matches[1][$i];
		}
	}
	$data_info["index_hot"] = $index_hot;

	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 7天天气
	$data = get_file_use_referer("http://www.weather.com.cn/weather/{$id}.shtml");
	$data_info["in_count"] ++;		// 抓取次数
	$data_info["in_flow"] += strlen($data);		// 本次抓取字节
	// 清理掉不需要的内容
	$data = skip_to_str($data, "<ul class=\"t clearfix\">");
	$_code_box = get_front_str($data, "</ul>");
	$day_7 = array();
	// 提取日期
	preg_match_all('/<h1>(.+?)<\/h1>/is', $_code_box, $matches);
	if(sizeof($matches[1])) {
		for($i=0; $i<sizeof($matches[1]); $i++) {
			$day_7[$i]["day"] = get_front_str($matches[1][$i], "日");
		}
	}
	// 匹配天气
	preg_match_all('/class=\"wea\">(.+?)<\/p>/is', $_code_box, $matches);
	if(sizeof($matches[1])) {
		for($i=0; $i<sizeof($matches[1]); $i++) {
			$day_7[$i]["weather"] = $matches[1][$i];
		}
	}
	// 匹配温度
	preg_match_all('/<span>(.+?)<\/span>\/<i>(.+?)℃<\/i>/is', $_code_box, $matches);
	if(sizeof($matches[1])) {
		for($i=0; $i<sizeof($matches[1]); $i++) {
			$day_7[$i]["temperature_1"] = $matches[1][$i]."℃";
			$day_7[$i]["temperature_2"] = $matches[2][$i]."℃";
		}
	}
	// 匹配风向
	preg_match_all('/<em>.*?title\=\"(.+?)\".*?title\=\"(.+?)\".*?<\/em>/is', $_code_box, $matches);
	if(sizeof($matches[1])) {
		for($i=0; $i<sizeof($matches[1]); $i++) {
			$day_7[$i]["wind_direction_1"] = $matches[1][$i];
			$day_7[$i]["wind_direction_2"] = $matches[2][$i];
		}
	}
	// 匹配风力
	preg_match_all('/<\/em>.*?<i>(.+?)<\/i>/is', $_code_box, $matches);
	if(sizeof($matches[1])) {
		for($i=0; $i<sizeof($matches[1]); $i++) {
			$day_7[$i]["wind_power"] = $matches[1][$i];
		}
	}
	$data_info["day_7"] = $day_7;

	////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// 15天天气
	$data = get_file_use_referer("http://www.weather.com.cn/weather15d/{$id}.shtml");
	$data_info["in_count"] ++;		// 抓取次数
	$data_info["in_flow"] += strlen($data);		// 本次抓取字节
	$data = skip_to_str($data, "<ul class=\"t clearfix\">");
	$_code_box = get_front_str($data, "</ul>");
	$day_15 = array();
	// 匹配日期
	preg_match_all('/<span class\=\"time\">.*?（(.+?)日）<\/span>/is', $_code_box, $matches);
	if(sizeof($matches[1])) {
		for($i=0; $i<sizeof($matches[1]); $i++) {
			$day_15[$i]["day"] = $matches[1][$i];
		}
	}
	// 匹配天气
	preg_match_all('/<span class\=\"wea\">(.+?)<\/span>/is', $_code_box, $matches);
	if(sizeof($matches[1])) {
		for($i=0; $i<sizeof($matches[1]); $i++) {
			$day_15[$i]["weather"] = $matches[1][$i];
		}
	}
	// 匹配温度
	preg_match_all('/<span class\=\"tem\"><em>(.+?)<\/em>\/(.+?)<\/span>/is', $_code_box, $matches);
	if(sizeof($matches[1])) {
		for($i=0; $i<sizeof($matches[1]); $i++) {
			$day_15[$i]["temperature"] = $matches[1][$i] . "/" . $matches[2][$i];
		}
	}
	// 匹配风向
	preg_match_all('/<span class\=\"wind\">(.+?)<\/span>/is', $_code_box, $matches);
	if(sizeof($matches[1])) {
		for($i=0; $i<sizeof($matches[1]); $i++) {
			$day_15[$i]["wind_direction"] = $matches[1][$i];
		}
	}
	// 匹配风力
	preg_match_all('/<span class\=\"wind1\">(.+?)<\/span>/is', $_code_box, $matches);
	if(sizeof($matches[1])) {
		for($i=0; $i<sizeof($matches[1]); $i++) {
			$day_15[$i]["wind_power"] = $matches[1][$i];
		}
	}
	$data_info["day_15"] = $day_15;


	return $data_info;

}
////////////////////////////////////////////////////////////////////////////////////////////








////////////////////////////////////////////////////////////////////////////////////////////
// 抓取天气预警信息
function get_weather_alarm(){
	set_time_limit(900);
	$alarm = array();
	$data = get_file_use_referer("http://product.weather.com.cn/alarm/grepalarm.php?areaid=[0-9]{5,7}");
	if(strlen($data)<256) return array();
	$alarm["in_flow"] = strlen($data);		// 抓取流量
	$data = skip_to_str($data, "var alarminfo=");
	$data = str_replace(";", "", $data);
	$data = json_decode($data, true);
	$data = $data["data"];
	// 读取全部的预警信息，很慢
	foreach($data as $d){
		$content = get_file_use_referer("http://www.weather.com.cn/data/alarm/". $d[1]);
		$alarm["in_flow"] += strlen($content);
		$content = skip_to_str($content, "var alarminfo=");
		$content = json_decode($content, true);
		unset($content["ALERTID"],$content["UNDERWRITER"],$content["STATIONNAME"]);
		$alarm[] = array(
				"province" => $content["PROVINCE"],
				"city" =>$content["CITY"],
				"signaltype" => $content["SIGNALTYPE"],
				"signallevel" => $content["SIGNALLEVEL"],
				"issuetime" => $content["ISSUETIME"],
				"issuecontent" => $content["ISSUECONTENT"],
		);
	}
	return $alarm;
}
////////////////////////////////////////////////////////////////////////////////////////////








////////////////////////////////////////////////////////////////////////////////////////////
// 伪装来源抓取网页，破解天气网限制
function get_file_use_referer($url, $rand=false){
	if($rand) $url .= "?_=". time();

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_TIMEOUT, 15);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_HEADER, 0);
	curl_setopt ($ch,CURLOPT_REFERER, "http://www.weather.com.cn");
	$data = curl_exec($ch);
	curl_close($ch);

	// 如果遇到防DDOS，则重新抓取，直到成功为止
	if(strpos($data, "System busy!")!==false) $data = get_file_use_referer($url, $rand=false);

	return $data;
}
// 普通方式抓取网页
function get_file($url=""){
	$opts = array('http'=>array('method'=>"GET",'timeout'=>15));
	$context = stream_context_create($opts);
	$content = file_get_contents($url, false, $context);
	return $content;
}

function csubstr($start,$end,$str){
	mb_internal_encoding("UTF-8");
	$p1 = mb_strpos($str,$start) + mb_strlen($start);
	$p2 = mb_strpos($str,$end);
	if($p1 === false || $p2 === false) return null;
	$p2 = $p2-$p1;
	return mb_substr($str,$p1,$p2);
}

function skip_to_str($data,$s){
	mb_internal_encoding("UTF-8");
	return mb_substr($data,mb_strpos($data,$s) + mb_strlen($s));
}

function get_front_str($data,$s){
	mb_internal_encoding("UTF-8");
	return mb_substr($data,0,mb_strpos($data,$s));
}

function unicode_urldecode($url){
	preg_match_all('/%u([[:alnum:]]{4})/', $url, $a);

	foreach ($a[1] as $uniord)
	{
		$dec = hexdec($uniord);
		$utf = '';

		if ($dec < 128){
			$utf = chr($dec);
		}
		else if ($dec < 2048){
			$utf = chr(192 + (($dec - ($dec % 64)) / 64));
			$utf .= chr(128 + ($dec % 64));
		}
		else{
			$utf = chr(224 + (($dec - ($dec % 4096)) / 4096));
			$utf .= chr(128 + ((($dec % 4096) - ($dec % 64)) / 64));
			$utf .= chr(128 + ($dec % 64));
		}

		$url = str_replace('%u'.$uniord, $utf, $url);
	}
	return urldecode($url);
}

function clear_html($s){
	$ret = strip_tags($s);
	$ret = str_replace(array("&nbsp;","&gt;"),"",$ret);
	return trim($ret);
}
////////////////////////////////////////////////////////////////////////////////////////////
?>